from django.shortcuts import render, redirect
from pyecharts import options as opts
from pyecharts.charts import Calendar
from django.contrib import messages, auth
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password
from fuzzywuzzy import process
from pyecharts.charts import Pie
from pyecharts.charts import Line
from email.mime.text import MIMEText
from email.header import Header
import pandas as pd
import smtplib
import fuzzywuzzy
import datetime
import random
import math


def remove_duplicate_item(items):
    empty_set = set()
    for item in items:
        if item not in empty_set:
            yield item
            empty_set.add(item)


def div_page(List, length):
    res = []
    s = 0
    while s + length <= len(List) - 1:
        res.append(List[s:s + length])
        s += length
    if s + length != len(List) - 1:
        res.append(List[s:])
    return res


def generate_code(length):
    str = ["{}".format(i) for i in range(10)]
    res = ""
    for i in range(length):
        res += random.choice(str)
    return res


def send_email_code(user_email):
    msg_from = "19802570583@163.com"
    authority_code = "CRKTZEJCROZWATIC"
    msg_to = user_email

    code = generate_code(6)
    subject = "统一身份登录"
    content = "您的验证码为:{}".format(code)
    msg = MIMEText(content)
    msg["Subject"] = subject
    msg["From"] = msg_from
    msg["To"] = msg_to

    try:
        s = smtplib.SMTP("smtp.163.com", 25)
        s.login(msg_from, authority_code)
        s.sendmail(msg_from, msg_to, msg.as_string())
        print("发送成功")
        return code
    except smtplib.SMTPException as e:
        print("发送失败")
        return None
    finally:
        s.quit()


def index(request):
    df = pd.read_csv("static/data/books.csv")
    book_list = df.sample(n=4)
    name = book_list['ISBN'].to_list()
    pic = book_list['图片地址'].to_list()
    book_name_1 = name[0]
    book_name_2 = name[1]
    book_name_3 = name[2]
    book_name_4 = name[3]
    book_pic_1 = pic[0]
    book_pic_2 = pic[1]
    book_pic_3 = pic[2]
    book_pic_4 = pic[3]

    pie_label = list(set(df["种类"]))
    percent = [len(df[df["种类"] == i]) for i in pie_label]
    # InitOpts(width="100px", height="100px")

    c1 = (
        Pie(init_opts=opts.InitOpts(
            width="500px",
            height='500px',
        ))
            .add("", [(pie_label[i], percent[i]) for i in range(len(percent))], radius=["40%", "60%"],
                 rosetype="radius")
            .set_global_opts(title_opts=opts.TitleOpts(
            title="本馆书籍种类分布情况",
            pos_left="center"),
            legend_opts=opts.LegendOpts(
                type_="scroll", pos_top="20%", pos_left="1%", orient="vertical", is_show=False,
            ),
        )
            .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))

    )

    time = ["{}月".format(i) for i in range(1, 13)]
    num1 = [random.randint(500, 1000) for i in range(12)]
    num2 = [random.randint(500, 1000) for i in range(12)]

    c2 = (
        Line(init_opts=opts.InitOpts(
            width="700px",
            height='400px',
        ))
            .add_xaxis(time)
            .add_yaxis("2019年", num1)
            .add_yaxis("2020年", num2)
            .set_global_opts(title_opts=opts.TitleOpts(title="图书借阅情况"),
                             yaxis_opts=opts.AxisOpts(min_=min(num1 + num2)))
    )

    begin = datetime.date(2020, 1, 1)
    end = datetime.date(2020, 12, 9)
    data = [
        [str(begin + datetime.timedelta(days=i)), random.randint(100, 250)]
        for i in range((end - begin).days + 1)
    ]

    c3 = (
        Calendar(init_opts=opts.InitOpts(
            width="600px",
            height='300px',
        ))
            .add("", data, calendar_opts=opts.CalendarOpts(range_="2020"))
            .set_global_opts(
            title_opts=opts.TitleOpts(title="图书馆每日借阅情况"),
            visualmap_opts=opts.VisualMapOpts(
                max_=300,
                min_=50,
                orient="horizontal",
                is_piecewise=True,
                pos_top="230px",
                pos_left="100px",
            ),
        )
    )

    dataset = {}
    dataset['book_name_1'] = book_name_1
    dataset['book_name_2'] = book_name_2
    dataset['book_name_3'] = book_name_3
    dataset['book_name_4'] = book_name_4
    dataset['book_pic_1'] = book_pic_1
    dataset['book_pic_2'] = book_pic_2
    dataset['book_pic_3'] = book_pic_3
    dataset['book_pic_4'] = book_pic_4
    dataset['species_distribution'] = c1.render_embed()
    dataset['annual_borrowing_situation'] = c2.render_embed()
    dataset['daily_borrowing_situation'] = c3.render_embed()
    return render(request, 'index.html', dataset)


def search_result_res(request):
    data = pd.read_csv("static/data/books.csv")
    L = list(set(data["种类"].tolist()))
    checkbox_status = [" " for i in range(len(L))]

    try:
        filter_list = list(request.POST)[1:]
        if filter_list:
            data = data[data["种类"].isin(filter_list)]
            for i in filter_list:
                checkbox_status[int(request.POST[i]) - 1] = "checked"
    except:
        pass
    L = [(L[i], checkbox_status[i]) for i in range(len(checkbox_status))]
    search_info = request.GET['search_info']
    L1 = []

    matches = fuzzywuzzy.process.extract("{}".format(search_info), data["书名"], limit=80,
                                         scorer=fuzzywuzzy.fuzz.token_sort_ratio)

    matches = list(remove_duplicate_item([i[0] for i in matches]))

    for match in matches:
        df = [i for i in data[data["书名"] == match].to_dict('index').values()][0]
        if len(df["书名"]) < 30 and len(df["作者"]) < 30:
            temp = ""
            for j in eval(df["作者"]):
                temp += "{} ".format(j)
            L1.append((df["书名"], df["种类"], df["图片地址"], temp, df["ISBN"]))

    try:
        page = int(request.GET['page'])
        max_num = math.ceil(len(L1) / 10)
        if page > max_num:
            messages.success(request, "本结果只有{}页".format(max_num))
        else:
            res = div_page(L1, 10)
            L1 = res[page - 1]
            print(len(L1))
    except:
        L1 = L1[:10]

    return render(request, 'search_result_res.html', {'search_result': L1, 'cata': L, "da": search_info})


def search_result_nav(request):
    return render(request, 'search_result_nav.html')


def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    elif request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(request, password=password, username=username)
        if user == None:
            messages.success(request, "用户名或密码错误")
            return render(request, 'login.html')
        else:
            return redirect('index')


def content(request):
    ISBN = request.GET['id']
    data = pd.read_csv("static/data/books.csv")
    df = [i for i in data[data["ISBN"] == ISBN].to_dict('index').values()][0]
    temp = ""
    for j in eval(df["作者"]):
        temp += "{} ".format(j)
    rad_book = (data[data["种类"] == df["种类"]]["图片地址"].sample(4)).to_list()

    data_dict = {'book1': rad_book[0], 'book2': rad_book[1], 'book3': rad_book[2], 'book4': rad_book[3],
                 'book_name': df["书名"], 'book_cata': df["种类"], 'book_pic': df["图片地址"], 'book_au': temp,
                 'book_isbn': df["ISBN"],
                 'book_pub': df['出版社'], 'book_time': df['出版时间'], 'book_money': df['价格'], 'book_num': df['数量']}
    return render(request, 'content.html', data_dict)


def sign_up(request):
    if request.method == 'GET':
        return render(request, 'signup.html')
    if request.method == 'POST':
        username = request.POST['userid']
        password1 = request.POST['password']
        password2 = request.POST['confirmPassword']
        email = request.POST['email']
        verifyMessage = request.POST['verifyMessage']

        if verifyMessage == '':
            code = send_email_code(email)
            f = open('static/config/config.txt', 'w')
            f.write(code)
            f.close()
        else:
            f = open('static/config/config.txt', 'r')
            code = f.read()
            f.close()
            if verifyMessage == code:
                if password1 == password2:
                    User.objects.create_user(username=username, password=password1)
                    return redirect('log_in')
                else:
                    return render(request, 'signup.html', {'error': '两次密码不一致'})

        data = {'userid': username,
                'password1': password1,
                'password2': password2,
                'email': email, 'verifyMessage': verifyMessage}

        return render(request, 'signup.html', data)
